package servlet;

import bean.Course;
import bean.User;
import dao.CourseDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ServletQueryCourse extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 按课程名搜索搜索
        String courseName = req.getParameter("query");

        // 处理 GET 请求中的参数编码问题
//        if (courseName != null) {
//            // 将获取的参数按 UTF-8 编码进行转换
//            courseName = new String(courseName.getBytes("ISO-8859-1"), "UTF-8");
//        }

        // 获取当前用户
        User user = (User)req.getSession().getAttribute("user");

        // 获取全部课程
        CourseDao courseDao = new CourseDao();
        List<Course> courseArrayList = courseDao.searchByCourseInfo(courseName,user);



        String title = "课程表";
        // 自定义排序[按lessonStart排序]
        courseArrayList.sort(new Comparator<Course>() {
            @Override
            public int compare(Course o1, Course o2) {
                return o1.getLessonStart() - o2.getLessonStart();
            }
        });

        // 设置属性，并且转发
        req.setAttribute("title", title);
        req.setAttribute("courseArrayList", courseArrayList);
        req.getRequestDispatcher("index.jsp").forward(req, resp);


    }
}
